#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
分析结果数据模型
"""

from typing import Dict, List, Optional, Any
from dataclasses import dataclass, field
from datetime import datetime

@dataclass
class AppInfo:
    """应用信息数据类"""
    name: str  # 应用名称
    version: Optional[str] = None  # 应用版本
    identifier: Optional[str] = None  # 应用标识符
    platform: str = "未知"  # 应用平台
    min_version: Optional[str] = None  # 最低系统版本要求
    size: Optional[int] = None  # 应用大小（字节）
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "name": self.name,
            "version": self.version,
            "identifier": self.identifier,
            "platform": self.platform,
            "min_version": self.min_version,
            "size": self.size
        }

@dataclass
class FrameworkInfo:
    """框架信息数据类"""
    name: str  # 框架名称
    version: Optional[str] = None  # 框架版本
    confidence: float = 1.0  # 置信度 (0-1)
    features: List[str] = field(default_factory=list)  # 识别到的特征
    files: List[str] = field(default_factory=list)  # 相关文件
    category: str = "未分类"  # 框架类别，如UI框架、网络框架等
    is_main: bool = False  # 是否是主要框架
    related_frameworks: List[str] = field(default_factory=list)  # 相关框架名称
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "name": self.name,
            "version": self.version,
            "confidence": self.confidence,
            "features": self.features,
            "files": self.files,
            "category": self.category,
            "is_main": self.is_main,
            "related_frameworks": self.related_frameworks
        }

@dataclass
class AnalysisResult:
    """应用分析结果数据类"""
    app_path: str  # 应用路径
    platform: str  # 应用平台
    app_name: Optional[str] = None  # 应用名称
    app_version: Optional[str] = None  # 应用版本
    frameworks: List[FrameworkInfo] = field(default_factory=list)  # 识别到的框架列表
    analysis_time: datetime = field(default_factory=datetime.now)  # 分析时间
    metadata: Dict[str, Any] = field(default_factory=dict)  # 其他元数据
    
    def add_framework(self, framework: FrameworkInfo) -> None:
        """添加识别到的框架"""
        self.frameworks.append(framework)
    
    def get_main_frameworks(self) -> List[FrameworkInfo]:
        """获取主要框架"""
        return [fw for fw in self.frameworks if fw.is_main]
    
    def get_frameworks_by_category(self) -> Dict[str, List[FrameworkInfo]]:
        """按类别获取框架"""
        result = {}
        for fw in self.frameworks:
            if fw.category not in result:
                result[fw.category] = []
            result[fw.category].append(fw)
        return result
    
    def analyze_framework_relationships(self) -> None:
        """分析框架间的关系"""
        # 按置信度排序框架
        sorted_frameworks = sorted(self.frameworks, key=lambda x: x.confidence, reverse=True)
        
        # 如果有框架，将置信度最高的标记为主框架
        if sorted_frameworks:
            sorted_frameworks[0].is_main = True
            
        # 分析框架关系
        for i, fw in enumerate(sorted_frameworks):
            # 查找相关框架
            for other_fw in sorted_frameworks:
                if fw.name != other_fw.name:
                    # 检查是否有共同的特征或文件
                    common_features = set(fw.features).intersection(set(other_fw.features))
                    common_files = set(fw.files).intersection(set(other_fw.files))
                    
                    if common_features or common_files:
                        if other_fw.name not in fw.related_frameworks:
                            fw.related_frameworks.append(other_fw.name)
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典格式"""
        return {
            "app_path": self.app_path,
            "platform": self.platform,
            "app_name": self.app_name,
            "app_version": self.app_version,
            "frameworks": [fw.to_dict() for fw in self.frameworks],
            "analysis_time": self.analysis_time.isoformat(),
            "metadata": self.metadata,
            "has_multiple_frameworks": len(self.frameworks) > 1,
            "framework_categories": list(self.get_frameworks_by_category().keys()),
            "main_frameworks": [fw.name for fw in self.get_main_frameworks()]
        }
    
    def summary(self) -> str:
        """生成分析结果概要信息"""
        summary_lines = [
            f"应用名称: {self.app_name or '未知'}",
            f"应用版本: {self.app_version or '未知'}"
        ]
        
        # 添加包名信息
        app_identifier = self.metadata.get("app_identifier")
        if app_identifier:
            summary_lines.append(f"包名/标识符: {app_identifier}")
        
        summary_lines.extend([
            f"分析平台: {self.platform}",
            f"分析时间: {self.analysis_time.strftime('%Y-%m-%d %H:%M:%S')}"
        ])
        
        if self.frameworks:
            # 先进行关系分析
            self.analyze_framework_relationships()
            
            # 获取主要框架和按类别分组的框架
            main_frameworks = self.get_main_frameworks()
            frameworks_by_category = self.get_frameworks_by_category()
            
            # 添加主要框架信息
            if main_frameworks:
                summary_lines.append("\n主要开发框架:")
                for i, fw in enumerate(main_frameworks, 1):
                    summary_lines.append(
                        f"{i}. {fw.name} {fw.version or ''} "
                        f"(置信度: {int(fw.confidence * 100) if 0 <= fw.confidence <= 1 else fw.confidence}%)"
                    )
            
            # 添加所有框架
            summary_lines.append("\n所有识别到的开发框架:")
            
            if len(frameworks_by_category) > 1:
                # 按类别显示框架
                for category, frameworks in frameworks_by_category.items():
                    summary_lines.append(f"\n{category}:")
                    for i, fw in enumerate(frameworks, 1):
                        summary_lines.append(
                            f"  {i}. {fw.name} {fw.version or ''} "
                            f"(置信度: {int(fw.confidence * 100) if 0 <= fw.confidence <= 1 else fw.confidence}%)"
                        )
                        # 显示相关框架
                        if fw.related_frameworks:
                            summary_lines.append(f"     相关框架: {', '.join(fw.related_frameworks)}")
            else:
                # 直接显示所有框架
                for i, fw in enumerate(self.frameworks, 1):
                    summary_lines.append(
                        f"{i}. {fw.name} {fw.version or ''} "
                        f"(置信度: {int(fw.confidence * 100) if 0 <= fw.confidence <= 1 else fw.confidence}%)"
                    )
                    # 显示相关框架
                    if fw.related_frameworks:
                        summary_lines.append(f"   相关框架: {', '.join(fw.related_frameworks)}")
        else:
            summary_lines.append("\n未识别到任何开发框架")
        
        return "\n".join(summary_lines) 
